import { defineStore } from 'pinia';
import { useStorage } from '@vueuse/core';
import LoginAPI from '@/api/admin/login';

// 公共信息类型结构
const DEFAULT_PUBLIC_INFO = {
  public_title: '',
  public_subtitle: '',
  public_logo: '',
  public_copyright: '',
  public_version: '',
  public_beian: '',
};

// API 请求失败时的 Fallback 数据
const FALLBACK_DATA = {
  public_title: 'Raise Admin',
  public_subtitle: '锐智后台管理系统',
  public_logo_raw: '../../assets/images/logo.png',
  public_copyright: 'Copyright ©2017-2024 raiseinfo.cn All Rights Reserved.',
  public_version: 'v1.0.0',
  public_beian: '鲁ICP备17046445号-4',
};

/**
 * 动态解析 src/assets 目录下的图片路径。
 *
 * @param {string} relativePath 相对于 store 文件位置的图片路径，例如：'../../assets/images/logo.png'
 * @returns {string} 解析后的图片 URL
 */
function resolveAssetUrl(relativePath) {
  try {
    if (!relativePath || typeof relativePath !== 'string') {
      return '';
    }
    return new URL(relativePath, import.meta.url).href;
  } catch (e) {
    console.error('Asset URL resolution failed:', e);
    return '';
  }
}

export const usePublicInfoStore = defineStore('publicInfo', () => {
  const publicInfo = useStorage('publicInfo', { ...DEFAULT_PUBLIC_INFO });
  /**
   * 负责加载公共信息，优先从 API 获取，失败则使用默认值。
   */
  async function loadPublicInfo() {
    if (publicInfo.value.public_title) {
      return;
    }
    try {
      const { data } = await LoginAPI.getPublicInfo();
      const apiData = { ...DEFAULT_PUBLIC_INFO, ...data };
      Object.assign(publicInfo.value, apiData);
    } catch (error) {
      console.error(
        'loadPublicInfo: API request failed, using fallback data.',
        error,
      );
      const fallbackData = {
        ...DEFAULT_PUBLIC_INFO,
        ...FALLBACK_DATA,
      };
      fallbackData.public_logo = resolveAssetUrl(FALLBACK_DATA.public_logo_raw);
      Object.assign(publicInfo.value, fallbackData);
    }
  }

  /**
   * 清除公共信息并重置 Store 状态。
   */
  function clearPublicInfo() {
    Object.assign(publicInfo.value, DEFAULT_PUBLIC_INFO);
  }

  return {
    publicInfo,
    loadPublicInfo,
    clearPublicInfo,
  };
});

export function usePublicInfoStoreHook() {
  return usePublicInfoStore(store);
}
